from rest_framework import serializers
from django.db import transaction
from goods.models import SKU, GoodsCategory, SpecificationOption, SPUSpecification, SKUSpecification


class SKUSpecificationSerializer(serializers.ModelSerializer):
    sku_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ("sku_id", "option_id")


class SKUSerialzier(serializers.ModelSerializer):
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    specs = SKUSpecificationSerializer(read_only=True, many=True)

    class Meta:
        model = SKU
        fields = "__all__"
        read_only_fields = ("spu", "category")

    @transaction.atomic()
    def create(self, validated_data):
        specs = self.initial_data.get('specs')

        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.create(**spec, sku=sku)

            except:
                transaction.savepoint_rollback(save_point)
                return serializers.ValidationError("sorry")
            else:
                transaction.savepoint_commit(save_point)
                return sku

    def update(self, instance, validated_data):
        specs = self.initial_data.get('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()

        try:
            SKU.objects.filter(id=instance.id).update(**validated_data)
            for spec in specs:
                SKUSpecification.objects.filter(sku=instance).update(**spec)
        except:
            transaction.savepoint_rollback(save_point)
            return serializers.ValidationError("sorry")
        else:
            transaction.savepoint_commit(save_point)
            return instance

class SKUCategorieSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ("id", "name")


class SPecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = "__all__"


class SPUSpecificationOptionSerializer(serializers.ModelSerializer):
    options = SPecificationOptionSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"
